package edu.cque.order.service;

import edu.cque.order.entity.Order;
import edu.cque.order.feign.AccountClient;
import edu.cque.order.feign.EasyIdGeneratorClient;
import edu.cque.order.feign.StorageClient;
import edu.cque.order.mapper.OrderMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.json.JsonParser;
import org.springframework.boot.json.JsonParserFactory;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * @author Hua
 * @create 2022-08-29 14:09
 */
@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    EasyIdGeneratorClient easyIdClient;
    @Autowired
    private AccountClient accountClient;
    @Autowired
    private StorageClient storageClient;


    @Override
    public void create(Order order) {
        // TODO: 从全局唯一id发号器获得id，这里暂时随机产生一个 orderId
//        Long orderId = Long.valueOf(new Random().nextInt(Integer.MAX_VALUE));
//        long orderId = Math.abs(new Random().nextLong());

        // 从全局唯一id发号器获得id
        String s = easyIdClient.nextId("order_business");
        JsonParser jsonParser = JsonParserFactory.getJsonParser();
        Map<String, Object> stringObjectMap = jsonParser.parseMap(s);
        Long orderId = Long.valueOf(stringObjectMap.get("data").toString());


        order.setId(orderId);
        orderMapper.create(order);


        // TODO: 调用storage，修改库存
        storageClient.decrease(order.getProductId(), order.getCount());

        // TODO: 调用account，修改账户余额
        accountClient.decrease(order.getUserId(), order.getMoney());
    }
}
